<template>
  <div class="app-container">
    <!--搜索表单-->
    <!-- <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input
          v-model="searchEmp.name"
          placeholder="请输入员工姓名"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchEmp.gender" placeholder="请选择">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="入职时间">
        <el-date-picker
          v-model="entrydate"
          clearable
          value-format="yyyy-MM-dd"
          type="daterange"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 400px; margin-left: 20px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form> -->

    <!--按钮-->
    <el-row>
      <el-button type="danger" size="medium" @click="deleteByIds">- 批量删除</el-button>
      <el-button type="primary" size="medium" @click="dialogVisible = true; emp = { image: ''};">+ 新增商品</el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑商品" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="good" label-width="80px" size="mini">

        <el-form-item label="商品名">
          <el-input v-model="good.name" />
        </el-form-item>
        <el-form-item label="最低价">
          <el-input v-model="good.minPrice" />
        </el-form-item>
        <el-form-item label="最高价">
          <el-input v-model="good.maxPrice" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="good.stock" />
        </el-form-item>

       <!-- <el-form-item label="性别">
          <el-select v-model="emp.gender" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in genderList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->


        <!-- 后面试试这个action="/api/upload" -->
        <el-form-item label="展示图片">
          <el-upload
            class="avatar-uploader"
            :action="upLoadUrl"
            :headers="token"
            name="image"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
          <img v-if="good.image" :src="good.image" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>


        <!-- <el-form-item label="展示图片">
          <el-upload
            class="avatar-uploader"
            :headers="token"
            action="/api/upload"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="emp.image" :src="emp.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item> -->

       <!-- <el-form-item label="展示图片">
        <el-upload
          action="http://192.168.43.60:9090/common/upload"
          list-type="picture-card"
          :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
        </el-upload>
        </el-form-item> -->

        <el-form-item label="商品分类">
          <el-select v-model="good.categoryName" placeholder="请选择" value-key="emp.job" style="width:100%">
            <el-option
              v-for="item in jobList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="展示html">
          <el-input v-model="good.content" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="商品名" align="center" />
        <el-table-column prop="image" label="图像" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 100px; border: none; cursor: pointer" :src="row.image" />
          </template>
        </el-table-column>
        <el-table-column prop="minPrice" label="最低价" align="center" />
        <el-table-column prop="maxPrice" label="最高价" align="center" />
        <el-table-column prop="stock" label="库存" align="center" />
        <el-table-column prop="categoryName" label="商品分类" align="center" />

        <!-- <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
              {{ scope.row.gender == "1" ? "男" : "女" }}</span>
          </template>
        </el-table-column> -->

       <!-- <el-table-column align="center" label="职位">
          <template slot-scope="scope">
            <span v-if="scope.row.job == 1" style="margin-right: 10px">班主任</span>
            <span v-if="scope.row.job == 2" style="margin-right: 10px">讲师</span>
            <span v-if="scope.row.job == 3" style="margin-right: 10px">学工主管</span>
            <span v-if="scope.row.job == 4" style="margin-right: 10px">教研主管</span>
          </template>
        </el-table-column> -->

        <!-- <el-table-column align="center" label="日职日期">
          <template slot-scope="scope">
            {{ scope.row.entrydate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后操作时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T',' '):'' }}
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="updateById(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <br>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById, findAll, loadFiles } from '@/api/emp.js'
// import { findAll } from '@/api/dept.js'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      /** 添加数据对话框是否展示的标记 */
      dialogVisible: false,
      // 品牌模型数据
      searchEmp: {
        name: '',
        gender: ''
      },

      /** 商品数据对象 */
      good: {
        name: '',
        image: '',
        minPrice: '',
        maxPrice: '',
        stock: '', // 库存
        categoryName: '', // 所属种类名
        content: '' // html
      },

      // deptList: [],
      // genderList: [{ id: 1, name: '男' }, { id: 2, name: '女' }],
      /** 商品分类列表，找后端拿 */
      jobList: [
        // {
        //   id: 1,
        //   name: '水果'
        // },
        // {
        //   id: 2,
        //   name: '文具'
        // },
        // {
        //   id: 3,
        //   name: '手机'
        // },
        // {
        //   id: 4,
        //   name: '。。。'
        // }
      ],

      // beginTime: '',
      // endTime: '',
      // entrydate: '',

      /** 被选中的id数组 */
      selectedIds: [],
      /** 复选框选中数据集合 */
      multipleSelection: [],

      /** 表格数据 */
      tableData: [
        {
          id: 10039,
          name: 'Apple iPhone 14 Pro Max 256G 银色 移动联通电信5G双卡双待手机',
          image: 'http://cba.itlike.com/public/uploads/10001/20230321/c4b5c61e46489bb9b9c0630002fbd69e.jpg',
          minPrice: '9989',
          maxPrice: '9988',
          stock: '20', // 库存
          categoryName: '手机' // 所属种类名
        }
      ],
      token: { token: getToken() },
      /** 图片上传的后端接口，但是这个是不能跨域的，默认后端解决了跨域问题，后面用request优化 */
      upLoadUrl: process.env.VUE_APP_URL + "common/upload"
    }
  },

  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0]
        this.endTime = val[1]
      } else {
        this.beginTime = ''
        this.endTime = ''
      }
    }
  },

  mounted() { // 钩子方法
    this.page() // 当页面加载完成后，发送异步请求，获取数据

    findAll().then((result) => { // 请求种类列表数据
      this.jobList = result.data.data
    })

    /**
     * 注意：这里默认后端解决了跨域问题，这里上传文件使用的直接是VUE_APP_URL，没有做跨域处理！！！
     */
    console.log(process.env.VUE_APP_URL)
  },

  methods: {
    /**
     * 查询分页数据
     */
    page() {
      page( // 向后端发请求
        this.currentPage,
        this.pageSize
      ).then((res) => {
        // 响应数据的data里面有total和records，去看接口文档
        this.totalCount = res.data.data.total
        this.tableData = res.data.data.records
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    // onSubmit() {
    //   this.currentPage = 1
    //   this.page()
    // },

    // clear() {
    //   this.searchEmp = { name: '', gender: '' }
    //   this.beginTime = ''
    //   this.endTime = ''
    //   this.entrydate = ''
    //   this.page()
    // },

    /**
     * 提交数据绑定的方法
     */
    add () {
      let operator

      console.log("categoryName")
      console.log(this.good.categoryName)

      console.log("jobList")
      console.log(this.jobList)

      // 将good.categoryName由id改成汉字
      if (!this.good.categoryName) {
        let categoryId = this.good.categoryName
        for (let i = 0; i < this.jobList.length; i++) {
          if (categoryId == this.jobList[i].id) {
            this.good.categoryName = this.jobList[i].name
          }
        }
      }

      // 如果是从修改来的，在点击编辑按钮时会先调用下面的updateById方法，请求后端接口后会返回查询的商品对象（有id属性），然后
      // 赋值给this.good，这样this.good就也有了id属性。
      if (this.good.id) {
        // 修改
        operator = update(this.good) // 后端接口
        console.log("修改good！！！！")
      } else {
        operator = add(this.good) // 后端接口
        console.log("新增good")
      }

      operator.then((resp) => {
        console.log(resp.data.status)
        if (resp.data.status == 200) { // 200
          this.dialogVisible = false
          this.page() // 刷新页面
          this.$message({ message: '保存成功！', type: 'success' })
          // 删掉this.good的id
          this.good = {
            name: '',
            image: '',
            minPrice: '',
            maxPrice: '',
            stock: '', // 库存
            categoryName: '', // 所属种类名
            content: '' // html
          }
        } else {
          // this.$message.error(resp.data.message)
          this.$message({ message: '保存失败！', type: 'error' })
        }
      })
    },

    /**
     * 根据id编辑商品数据

     * @param {Object} id
     */
    updateById (id) {
      // 打开编辑窗口
      this.dialogVisible = true

      // 请求后端接口，根据id查询商品
      selectById(id).then((result) => {
        if (result.data.status == 200) { // 200
          this.good = result.data.data // 将返回的商品对象赋值给this.good，此时this.good里面有id属性了，同时展示的表格里面也有回显数据了
          this.good
        }
      })
    },

    /**
     * 分页

     * @param {Object} val
     */
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val
      this.page()
    },

    /**
     * 删除员工信息

     * @param {Object} id
     */
    deleteById (id) {
      this.$confirm('此操作将删除该数据, 真的要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 请求后端接口
        deleteById(id).then((resp) => {
          if (resp.data.status == 200) { // 200
            // 删除成功
            this.$message.success('删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    /**
     * 批量删除员工信息
     */
    deleteByIds () {
      // 弹出确认提示框
      this.$confirm('此操作将删除所有选中的数据, 真的要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确认按钮
        // 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id
        }

        // 发送AJAX请求
        deleteById(this.selectedIds).then((resp) => {
          if (resp.data.status == 200) {
            // 删除成功
            this.$message.success('删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    /**
     * 文件上传相关

     * @param {Object} res
     * @param {Object} file
     */
    handleAvatarSuccess(res, file) {
      // this.emp.image = res.data
      // console.log(this.emp.image)
      console.log("返回数据：：：")
      console.log(res.data)

      this.good.image = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      console.log("file: ")
      console.log(file)

      return isJPG && isLt2M
    }

    // handleRemove(file) {
    //         console.log(file);
    //       },
    //       handlePictureCardPreview(file) {
    //         this.dialogImageUrl = file.url;
    //         this.dialogVisible = true;
    //       },
    //       handleDownload(file) {
    //         console.log(file);
    //       }
  }
}
</script>
<style>
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
} */

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
